package cn.wolfcode.web.modules.customer.service.impl;

import cn.wolfcode.web.modules.customer.entity.Customer;
import cn.wolfcode.web.modules.customer.mapper.CustomerMapper;
import cn.wolfcode.web.modules.customer.service.ICustomerService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import link.ahsj.core.utils.base.AppAssertUtil;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 客户信息 服务实现类
 * </p>
 *
 * @author tangzehua
 * @since 2022-06-20
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {

    @Override
    public IPage<Customer> pageCustomer(Integer page, Integer pageSize, String name) {
        IPage<Customer> customerPage = new Page<>(page, pageSize);
        customerPage = baseMapper.pageCustomer(customerPage, name);
        return customerPage;
    }

    @Override
    public Boolean insert(Customer entity) {

        LambdaQueryWrapper<Customer> nameWrapper = new LambdaQueryWrapper<>();
        nameWrapper.eq(Customer::getCustomerName,entity.getCustomerName());
        if(list(nameWrapper).size()>0){
            // 抛异常
            AppAssertUtil.err("该企业名称已存在");
        }

        repCapital(entity.getRegCapital());

        return save(entity);
    }

    @Override
    public Boolean updateMy(Customer entity) {
        LambdaQueryWrapper<Customer> nameWrapper = new LambdaQueryWrapper<>();
        nameWrapper.eq(Customer::getCustomerName,entity.getCustomerName());

        Customer one = getOne(nameWrapper);

        if(one!=null && !one.getId().equals(entity.getId())){
            AppAssertUtil.err("企业名已被占用");
        }

        repCapital(entity.getRegCapital());

        return updateById(entity);
    }

    public void repCapital(String repCapital){
        Integer regCapital = 0;

        try {
            regCapital= Integer.valueOf(repCapital);
        } catch (NumberFormatException e) {
            AppAssertUtil.err("资金只能用正整数表示");
        }

        if(regCapital <= 0){
            AppAssertUtil.err("请输入合理的注册资金");
        }
    }
}
